/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.StringTokenizer;

import org.w3c.dom.Document;

import cgl.narada.matching.xpath.Query;
import cgl.narada.matching.xpath.XPathProfile;
import cgl.narada.matching.xpath.XmlEvent;
import cgl.narada.protocol.DataReceived;
import cgl.narada.protocol.Handler;
import cgl.narada.protocol.Protocol;
import cgl.narada.transport.TransportException;
import cgl.narada.transport.TransportHandler;
import cgl.narada.transport.TransportHandlerImpl;
import cgl.narada.util.ByteUtilities;

public class XmlEventComm implements Handler {
  String moduleName = "XmlEventComm: ";
  int assignedId=0;

  /** Deals with the transport related aspects of communication */
  private TransportHandler transportHandler;


  public XmlEventComm() {
    transportHandler = new TransportHandlerImpl(this);
  }

  public void loadCommunicationsOfType(Properties commProps, String commType) {
    try {
      transportHandler.loadCommunicationsOfType(commProps, commType);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
  }
  
  public String createLinkTo(Properties props, String linkType) {
    try {
      return transportHandler.setupLink(props, linkType);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
    return null;
  }
  

  public void sendDataTo(byte[] data, String node) {
    try {
      transportHandler.sendData(data, node);
    } catch (TransportException transEx) {
      System.out.println(transEx);
    }
  }

  /** This method indicates that the node in question is a client */
  public boolean isClient() {
    return true;
  }
  
  public void sendNodeAddressRequestTo(String node) {
    byte[] data = new byte[1];
    data[0] =  Protocol.NAP_CLIENT_ADD;
    sendDataTo(data, node);
  }

  
  public void subscribeTo(String subscribeTo, String node) {
    XPathProfile  xPathProfile = 
      new XPathProfile(subscribeTo, node, assignedId);
    byte[] profileBytes = xPathProfile.getBytes();
    int profileLength  = profileBytes.length;
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(baOutputStream);
    
    try {
      dout.writeByte(Protocol.XPATH_CLIENT_ADD_PROFILE);
      dout.writeInt(profileLength);
      dout.write(profileBytes);
      
    } catch (IOException ioe) {
      System.out.println(moduleName + "Error marshalling stream" + ioe);
    } /* end try-catch */
    sendDataTo(baOutputStream.toByteArray(), node);
  }
  
  
  public void propagateEventToBroker(Document document, String node) {
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(baOutputStream);
    XmlEvent xmlEvent = new XmlEvent(assignedId, document);
    byte[] xmlEventBytes = xmlEvent.getBytes();
    System.out.println("Value of xmlEventBytes[0]=" + xmlEventBytes[0]);
    try {
      dout.writeByte(Protocol.NARADA_XML_CLIENT_EVENT);
      dout.writeInt(xmlEventBytes.length);
      dout.write(xmlEventBytes);   
    } catch (IOException ioe) {
      System.out.println(moduleName + "Error marshalling stream" + ioe);
    } /* end try-catch */
    byte [] dataToSend = baOutputStream.toByteArray();
    System.out.println("Length = " + xmlEventBytes.length );
    sendDataTo(dataToSend, node);
  }
  
  public void handleData(byte[] data, String sender) {
       
    if (data.length == 0) {
      System.out.println(moduleName + "Data received has length = 0");
      return;
    }
    int dataInfo = (int) data[0];
    
    switch(dataInfo) {
    case (int) Protocol.NARADA_XML_EVENT:
      System.out.println("Received Narada-XML event");
      XmlEvent xmlEvent = new XmlEvent(data);
      System.out.println(xmlEvent);
      break;
      
    case (int) Protocol.NAP_CLIENT_ADD_RESPONSE:
      processNodeAddressResponse(sender, data);
      break;
 
    default: 
      System.out.println("Error::Data[0] ->" + dataInfo +
			 " Data length = " + data.length);
      break;
    } /*end switch-case */ 
  } 

  public void processNodeAddressResponse(String sender,
					 byte[] addressResponse) {
    if (addressResponse.length == 1) {
      System.out.println("This server node ("+ sender + 
			 ") hasn't been assigned an address yet ");
    }
    if (addressResponse.length ==2) {
      System.out.println("The system has exceeded its capacity to handle" + 
			 " clients, please try at a different node ");
    }
    
    int offset =0;
    offset++; /** Skipping the header */
    byte[] destinationBytes = new byte[4];
    System.arraycopy(addressResponse, offset,
		     destinationBytes, 0, 4);
    assignedId = ByteUtilities.getInt(destinationBytes);
    System.out.println("Assigned Id= " + assignedId);
  }


  public static void main(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: java cgl.narada.test.XmlEventComm <portnum>");
      System.exit(0);
    }
    XmlEventComm endpoint = new XmlEventComm();
    Properties props = new Properties();
    props.put("TCPServerPort", "0");
    endpoint.loadCommunicationsOfType(props, "tcp");
    
    
    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok;
    String cmd;
    while (true) {
      try {
	cmd = r.readLine();
	if (cmd == null) {
	  break;
	}

	if(cmd.startsWith("h")) {
	  System.out.println("Create Link          -> cr hostname portNum ");
	  System.out.println("Send NodeAddresReq   -> na  linkId");
	  System.out.println("Subscribe To         -> s   topic linkId");
	  System.out.println("Send Data To         -> sd  xmlFile linkId" );
	}
	
	if (cmd.startsWith("cr")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "cr" */
	  Properties linkProps = new Properties();
	  linkProps.put("hostname", tok.nextToken());
	  linkProps.put("portnum", tok.nextToken());
	  String _linkId = endpoint.createLinkTo(linkProps, "tcp");
	  System.out.println("Created link with id => " + _linkId); 
	  continue;
	} /** end create link */
	
	if (cmd.startsWith("na")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "na" */
	  String _linkId = tok.nextToken();
	  endpoint.sendNodeAddressRequestTo(_linkId);
	  continue;
	} /*end node address request */

	if (cmd.startsWith("s ")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "sd" */
	  String _topic = tok.nextToken();
	  String _linkId = tok.nextToken();
	  endpoint.subscribeTo(_topic, _linkId);
	  continue;

	} /* end subscribe to */

	if (cmd.startsWith("sd ")) {
	  tok = new StringTokenizer(cmd, " ");
	  tok.nextToken(); /* skipping the token "s" */
	  String _fileLoc = tok.nextToken();
	  String _linkId = tok.nextToken();
	  Query query = new Query();
	  Document _doc = query.getDocumentFromFile(_fileLoc); 
	  if (_doc == null) {
	    System.out.println("Invalid file :: Try again");
	    continue;
	  }
	  endpoint.propagateEventToBroker(_doc, _linkId);
	  continue;
	} /* end send data */
	

      }catch (IOException ioe) {
	ioe.printStackTrace();
      } /* end try-catch */
    } /* end while(true) */
    
    System.out.println("Terminating program ....");

  }/*end main() */
  
}
